package com.leon.androidui.customview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Scroller;

import androidx.annotation.Nullable;

public class RulerView extends View {

    private Paint flagPaint = new Paint();
    private Paint tickMarkPaint = new Paint();
    private Paint tickMarkTextPaint = new Paint();
    private Paint unitPaint = new Paint();

    private int normarTickMarkHeight = 60;
    private int intTickMarkHeight = 100;
    private int normrTickSpace = 20;

    private int translationX = 0;
    private float downX;

    private String text;
    private float textWidth;
    private int current;

    private VelocityTracker mVelocityTracker;
    private int mMinimumFlingVelocity;
    private int mMaximumFlingVelocity;
    private FlingRunnable fling;

    public RulerView(Context context) {
        super(context);
        initView(context, null);
    }

    public RulerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context, null);
    }

    public RulerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, null);

    }

    private void initView(Context context, AttributeSet attrs) {
        fling = new FlingRunnable(context);

        ViewConfiguration configuration = ViewConfiguration.get(context);
        mMinimumFlingVelocity = configuration.getScaledMinimumFlingVelocity();
        mMaximumFlingVelocity = configuration.getScaledMaximumFlingVelocity();

        flagPaint.setColor(Color.parseColor("#4abb73"));
        flagPaint.setStyle(Paint.Style.FILL);
        flagPaint.setStrokeCap(Paint.Cap.ROUND);
        flagPaint.setTextSize(160);
        flagPaint.setStrokeWidth(8);

        unitPaint.setColor(Color.parseColor("#4abb73"));
        unitPaint.setTextSize(80);

        tickMarkPaint.setColor(Color.parseColor("#e2e5e2"));
        tickMarkPaint.setStyle(Paint.Style.FILL);
        tickMarkPaint.setStrokeCap(Paint.Cap.ROUND);
        tickMarkPaint.setStrokeWidth(4);

        tickMarkTextPaint.setTextSize(40);
        tickMarkTextPaint.setColor(Color.parseColor("#000000"));
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 阻止外层容器viewgroup拦截
        this.getParent().requestDisallowInterceptTouchEvent(true);

        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(event);

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                int deltaX = (int) (event.getX() - downX);
                translationX += deltaX;
                downX = event.getX();
                if (translationX >= getWidth() / 2) {
                    translationX = getWidth() / 2;
                }
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                deltaX = (int) (event.getX() - downX);
                translationX += deltaX;
                translationX = (translationX + normrTickSpace / 2) / normrTickSpace * normrTickSpace;
                if (translationX >= getWidth() / 2) {
                    translationX = getWidth() / 2;
                }
                invalidate();
                // 计算当前速度， 1000表示每秒像素数等
                mVelocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity);
                final float velocityY = mVelocityTracker.getYVelocity();
                final float velocityX = mVelocityTracker.getXVelocity();

                if ((Math.abs(velocityY) > mMinimumFlingVelocity)
                        || (Math.abs(velocityX) > mMinimumFlingVelocity)) {
                    Log.d("leon", "-->onTouchEvent: velocityX:" + velocityX + " velocityY:" + velocityY);
                    int velocit = (int) ((velocityX + normrTickSpace / 2) / normrTickSpace * normrTickSpace);
                    fling.start(translationX, velocit, -40000, getWidth() / 2);
                }

                if (mVelocityTracker != null) {
                    mVelocityTracker.recycle();
                    mVelocityTracker = null;
                }

                break;
        }
        return true;
    }

    private class FlingRunnable implements Runnable {
        private Scroller mScroller;

        private int mInitX;
        private int mMinX;
        private int mMaxX;
        private int mVelocityX;

        public FlingRunnable(Context context) {
            this.mScroller = new Scroller(context, null, false);

        }

        void start(int initX, int velocityX, int minX, int maxX) {
            this.mInitX = initX;
            this.mVelocityX = velocityX;
            this.mMinX = minX;
            this.mMaxX = maxX;
            // 先停止上一次的滚动
            if (!mScroller.isFinished()) {
                mScroller.abortAnimation();
            }

            mScroller.fling(initX, 0, velocityX, 0, minX, maxX, 0, 0);
            post(this);
        }

        @Override
        public void run() {
            if (!mScroller.computeScrollOffset()) {
                return;
            }

            int currX = mScroller.getCurrX();
            int diffx = currX - mInitX;
            if (diffx == 0) {
                return;
            }

            translationX += diffx;
//            translationX = (translationX + normrTickSpace / 2) / normrTickSpace * normrTickSpace;
            if (translationX >= getWidth() / 2) {
                translationX = getWidth() / 2;
            }
            invalidate();
            Log.d("leon", "-->onFling run: translationX:" + translationX + " currX:" + currX + " diffx:" + diffx + " mInitX:" + mInitX);

            mInitX = currX;
            post(this);


        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.save();
        canvas.translate(translationX, 0);
        int centerY = getHeight() / 2;
        int centerX = getWidth() / 2;
        int width = getWidth();
        int startX = 0;
        if (translationX <= 0) {
            startX = startX - translationX;
        }
        Log.d("leon", "-->onDraw: translationX:" + translationX + " width:" + width + " normrTickSpace:" + normrTickSpace + " startX:" + startX);
        int startY = centerY;
        // 画顶部灰色横线
        canvas.drawLine(startX, centerY, startX + width - translationX, centerY, tickMarkPaint);
        int num;
        for (int i = 0; i <= (width - translationX) / normrTickSpace; i++) {
            num = ((startX / normrTickSpace) + i);
            if (num % 10 == 0) {
                // 画整数刻度线 和 指示值
                canvas.drawLine(startX + i * normrTickSpace, startY, startX + i * normrTickSpace, startY + intTickMarkHeight, tickMarkPaint);
                text = num / 10 + "";
                textWidth = tickMarkTextPaint.measureText(text);
                canvas.drawText(text, startX + i * normrTickSpace - textWidth / 2, startY + intTickMarkHeight + 80, tickMarkTextPaint);
            } else {
                // 画非整数刻度线
                canvas.drawLine(startX + i * normrTickSpace, startY, startX + i * normrTickSpace, startY + normarTickMarkHeight, tickMarkPaint);
            }
        }

        canvas.restore();

        current = (getWidth() / 2 - translationX) / normrTickSpace;

        canvas.drawLine(centerX, centerY, centerX, centerY + intTickMarkHeight + 30, flagPaint);

        String currentText = current / 10.0f + "";
        float textWidth = flagPaint.measureText(currentText);
        // 当前选中值
        canvas.drawText(currentText, centerX - textWidth / 2, centerY - 200, flagPaint);
        // 单位
        canvas.drawText("kg", centerX + textWidth / 2 + 10, centerY - 280, unitPaint);
    }
}
